const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 获取所有分类
router.get('/categories', (req, res) => {
  db.query('SELECT * FROM categories ORDER BY name', (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json(results);
  });
});

// 创建分类
router.post('/categories', (req, res) => {
  const { name, description } = req.body;
  
  db.query(
    'INSERT INTO categories (name, description) VALUES (?, ?)',
    [name, description],
    (error, results) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ 
        id: results.insertId, 
        message: '分类创建成功' 
      });
    }
  );
});

// 获取分类下的帖子
router.get('/categories/:id/posts', (req, res) => {
  const { id } = req.params;
  
  db.query(`
    SELECT p.*, u.username, 
           (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count
    FROM posts p
    JOIN users u ON p.user_id = u.id
    WHERE p.category_id = ?
    ORDER BY p.created_at DESC
  `, [id], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json(results);
  });
});

module.exports = router; 